//index.js
//获取应用实例
require('../../utils/api.js');
let user = require('../../utils/user.js');
user.isLogin();
const app = getApp()

function in_array(val, array) {
  console.log(val, array)
  for (var i = 0; i < array.length; i++) {
    if (val == array[i]) {
      return true;
    }
  }
  return false;
}
Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    devices: [], // 搜索到的蓝牙设备
    hasUserInfo: false,
    searchText: '',
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function() {
    let vm = this;
    wx.getStorage({
      key: 'current_device',
      success: function(res) {
        vm.setData({
          devices: [res.data]
        });
      },
    });
    // 确保用户登录
    user.realLogin(function(res) {
      if ("SUCCESS" != res.status) {
        wx.setStorageSync('token', '');
        wx.setStorageSync('member', null);
        wx.redirectTo({
          url: '/pages/password_login/password_login',
        });
      } else {
        console.log('当前已经登录');
      }
    });

  },
  openBluetooth: function() {
    console.log('Opening bluetooth');
    wx.openBluetoothAdapter({
      success: function(res) {
        console.log('Success:', res);
      },
      fail: function(res) {
        console.log('Open Failed:', res);
      },
    })
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  /**
   * 蓝牙连接
   */
  connect: function(e) {
    let vm = this,
      uid = e.currentTarget.dataset.uid,
      name = e.currentTarget.dataset.name;
    vm.openBluetooth();
    console.log(arguments);
    wx.getConnectedBluetoothDevices({
      services: [],
      success: function(res) {
        let devices = res.devices,
          connected = false;
        console.log(devices);
        for (let i = 0; i < devices.length; i++) {
          if (devices[i].deviceId === uid) {
            // 已连接不需要再连接
            connected = true;
            console.log(name + '已经连接~');
            wx.navigateTo({
              url: '/pages/detail/detail',
            });
            return false;
          } else {
            // 关闭其他设备的连接
            wx.closeBLEConnection({
              deviceId: devices[i].deviceId,
              success: function(res) {
                console.log(res, devices[i].name + '-断开连接。')
              },
            })
          }

        }
        console.log("connected is false");
        // 未连接再连接
        if (!connected) {
          vm.connectBLE({
            deviceId: uid,
            name: name
          });

        }
      },
      fail: function(res) {
        console.log(res);
      },
    })
  },
  connectBLE: function(device) {
    if (!device || !device.deviceId) {
      wx.showModal({
        title: '提示',
        content: '蓝牙参数异常无法连接',
      })
      return false;
    }
    // if (device.name != 'BJQ602') {
    //   wx.showModal({
    //     title: '提示',
    //     content: '非法蓝牙无法连接',
    //   });
    //   return false;
    // }
    wx.showToast({
      icon: 'loading',
      title: '连接中',
      duration: 15000,
    })
    console.log('connecting BLE...', device.deviceId, device);
    let vm = this;
    wx.createBLEConnection({
      deviceId: device.deviceId,
      success: function(res) {
        wx.showToast({
          title: '连接成功',
        })
        console.log(device.name + '连接成功');
        let chars = [];
        wx.setStorage({
          key: 'current_device',
          data: device,
          success: function(res) {
            for (let i = 0; i < vm.data.devices; i++) {
              if (vm.data.devices[i].deviceId === device.deviceId) {
                let device = vm.data.devices[i].uid;
                vm.setData({
                  devices: [device]
                });
              }
            }
            wx.navigateTo({
              url: '../detail/detail',
            })
            console.log(res);
          }
        })
      },
      fail: function(res) {
        wx.showToast({
          icon: 'none',
          title: '连接失败',
        })
        console.log(res);
      },
    })
  },
  /**
   * 搜索蓝牙
   */
  searchBluetooth: function(e) {
    let vm = this;
    console.log(vm.data);
    vm.setData({
      searchText: '正在搜索设备...'
    });
    vm.openBluetooth();
    // 初始化蓝牙模块
    wx.getBluetoothAdapterState({
      success: function(res) {
        console.log(res);
        if (!res.available) {
          wx.showModal({
            title: '提示',
            content: '请先打开蓝牙功能！',
          })
          return false;
        }
        wx.startBluetoothDevicesDiscovery({
          success: function(res) {
            console.log(res);
            // 获取蓝牙设备列表
            wx.getBluetoothDevices({
              success: function(res) {
                console.log(JSON.stringify(res.devices));
                if (!res.devices || res.devices.length == 0) {
                  wx.showModal({
                    title: '提示',
                    content: '无可用的蓝牙设备',
                  });
                }

                let devices = [];
                let macId = [];
                for (let i = 0; i < res.devices.length; i++) {
                  let temp = res.devices[i];
                  console.log(temp.deviceId +'-'+temp.name);
                  if ('未知设备' != temp.name && !in_array(temp.deviceId, macId)) {
                    macId.push(temp.deviceId);
                    devices.push(temp);
                  }
                }
                console.log(devices);
                wx.showModal({
                  title: '提示',
                  content: '共找个设备数：' + devices.length,
                })
                vm.setData({
                  devices: devices
                });
              },
            });
            vm.setData({
              searchText: ''
            });
          },
          fail: function(res) {
            wx.showModal({
              title: '提示',
              content: '无可用的蓝牙设备',
            });
            vm.setData({
              searchText: ''
            });
          }
        })
      },
      fail: function(res) {
        console.log(res);
        wx.showModal({
          title: '提示',
          content: '蓝牙未打开，请先打开蓝牙模块',
        })
        vm.setData({
          searchText: ''
        });
      }
    })
  },
})